package cn.bjtu.shakingnewsbrowser;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Paint;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import cn.bjtu.shakingnewsbrowser.R;

public class ShakingActivity extends AppCompatActivity implements SensorEventListener {
    ImageView mainImg;
    Button btnReturn;
    TextView goWeb;
    View shakeCanTouchView;
    SensorManager sensorManager;
    Boolean isVisable = false;
    Context context = this;


    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            hideSystemUI();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shaking);
        init();
    }

    private void init() {
//        初始化控件
        mainImg = findViewById(R.id.shakingImg);
        btnReturn = findViewById(R.id.btn_return);
        goWeb = findViewById(R.id.go_web);
        shakeCanTouchView = findViewById(R.id.shake_can_touch_view);
        goWeb.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);

        btnReturn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();  //直接关闭当前页面
            }
        });
        goWeb.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(ShakingActivity.this, NewsActivity.class);
                startActivity(intent);
            }
        });
        shakeCanTouchView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //有按下动作时调出菜单
                if (isVisable) {
                    hideSystemUI();
                } else {
                    showSystemUI();
                }
                isVisable = !isVisable;
            }
        });
    }

    private void setSensor() {
//      1. 获得传感器管理者对象
        sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
//      2. 获取需要的传感器对象（加速度传感器）
        Sensor accSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
//      3. 注册传感器所需的监听器
        sensorManager.registerListener((SensorEventListener) context, accSensor, SensorManager.SENSOR_DELAY_NORMAL);
    }

    @Override
    protected void onStart() {
        super.onStart();
        setSensor();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    @Override
    public void onSensorChanged(SensorEvent sensorEvent) {
//        传感器数值改变时会调用的方法
        float[] values = sensorEvent.values;
        float x = values[0];
        float y = values[1];
        float z = values[2];
//        小幅度摇晃时，手机不会发生变化; 大幅度摇晃时，手机开启摇一摇
        int minValue = 12;
        if (Math.abs(x) > minValue || Math.abs(y) > minValue || Math.abs(z) > minValue) {
//          开始摇一摇动画（使用补间动画中的旋转动画）
            anmi();
        }
    }

    private void anmi() {
        //xml文件 实现动画执行
        @SuppressLint("ResourceType") Animation animation = AnimationUtils.loadAnimation(this, R.xml.rotate_anim);
        animation.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                //动画开始回调方法
                //      4. 注销传感器的监听器
                sensorManager.unregisterListener((SensorEventListener) context);
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                //动画结束
                mainImg.clearAnimation();
                Intent intent = new Intent(ShakingActivity.this, RanSentenceActivity.class);
                startActivity(intent);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {
                //动画重复执行
            }
        });
        mainImg.startAnimation(animation);
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int i) {
//        传感器精度改变会调用的方法
    }

    private void hideSystemUI() {
        // Enables regular immersive mode.
        // For "lean back" mode, remove SYSTEM_UI_FLAG_IMMERSIVE.
        // Or for "sticky immersive," replace it with SYSTEM_UI_FLAG_IMMERSIVE_STICKY
        View decorView = getWindow().getDecorView();
        decorView.setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_IMMERSIVE
                        // Set the content to appear under the system bars so that the
                        // content doesn't resize when the system bars hide and show.
                        | View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        // Hide the nav bar and status bar
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_FULLSCREEN);
        btnReturn.setVisibility(View.GONE);
    }

    // Shows the system bars by removing all the flags
    // except for the ones that make the content appear under the system bars.
    private void showSystemUI() {
        View decorView = getWindow().getDecorView();
        decorView.setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
        btnReturn.setVisibility(View.VISIBLE);
    }

}